package com.xu.common.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.xu.common.consts.XuConst;
import com.xu.common.exception.MyException;
import com.xu.modules.entity.PersonalUserEntity;
import com.xu.modules.service.vo.PersonalUserVo;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;


/**
 * token 工具类
 *
 * @author xu
 * 2022/7/20 15:14
 */
@Component
public record TokenUtil(RedisCache redisCache) {
    /**
     * 获取用户信息
     */
    public PersonalUserVo getUserInfo() {
        HttpServletRequest request = ServletUtils.getRequest();
        String token = request.getHeader(XuConst.REQUEST_HEADER);

        if(StrUtil.isBlank(token)){
            throw new MyException("请先登录");
        }

        Object obj = redisCache.getCacheObject(XuConst.TOKEN_KEY + token);
        if(null == obj){
            throw new MyException("请先登录");
        }
        // 强行转换
        return Convert.convert(PersonalUserVo.class, obj);
    }

    /**
     * token 存储
     */
    public String setToken(PersonalUserEntity personalUserEntity){
        // 转换为个人信息展示
        PersonalUserVo personalUserVo = BeanUtil.copyProperties(personalUserEntity, PersonalUserVo.class);
        // 生成信息token信息
        String token = IdUtil.simpleUUID();
        // 存入redis
        redisCache.setCacheObject(XuConst.TOKEN_KEY + token,personalUserVo);
        return token;
    }
}
